import axios from "axios";
//引入自己写的axios
import api from '../../http/apis/api.js'

export default {
  //状态，保存数据
  namespaced: true,
  state: {
    searchdata: {
      type: 'categoryName',
      value: '',
    },
    pageData: {
      currentPage: 1,
      pageSize: 5,
      totalNum: 3,
      totalPages: 1,
      data: [],
    },
    update:{}
  },
  //修改state里面的属性值唯一方法就是使用mutations
  mutations: {
      //获取的新页数
    setpageData(state, newpageData) {
      state.pageData = newpageData;

    },
    //获取修改的学生数据并赋值
    updatecategory(state, category) {
      state.update = category;
    },
    //改变显示页数
    changeshowpage(state, newpage) {
      state.pageData.pageSize = newpage;
    },
    //首页
    firstpage(state) {
      state.pageData.currentPage = 1;
    },
    //尾页
    endpage(state) {
      state.pageData.currentPage = state.pageData.totalPages;
    },
    //上一页
    lastpage(state) {
      if (state.pageData.currentPage > 1)
        state.pageData.currentPage--;
    },
    //下一页
    nextpage(state) {
      if (state.pageData.currentPage < state.pageData.totalPages) {
        state.pageData.currentPage++;
      }
    },
  },
  //异步操作
  actions: {
     //获取
    async showCategorys(context,{type,value}={}) {
        const { data } = await api.category.showCategorys({
          currentPage: context.state.pageData.currentPage,
          pageSize: context.state.pageData.pageSize,
          type: context.state.searchdata.type,
          value: context.state.searchdata.value,
        });
        if(data.status){
          context.commit('setpageData', data.data)
        }
    },
    //删除
    async delectone(context, _id) {
      const { data } = await api.category.delectone({_id});
      console.log(data);
      context.dispatch('showCategorys')
      // return data;                                   
    },
    //新增
    async addcategory(context, category) {
      const {data}  = await api.category.addcategory({...category})
      //如果返回的数据成功
      return data;
    },
    //获取修改的id
    async getcategoryid(context,_id){
      const {data} = await api.category.getcategoryid(_id);
      if(data.status){
        context.commit('updatecategory', data.data[0])
      }
    },
     //点击确认修改
    async updatecategory(context, newcategory) {
      const { data } = await api.category.updatecategory({ ...newcategory })
      return data;
    }
  }
}